package com.wut.jmx.filter;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSON;
import com.wut.jmx.common.BaseContext;
import com.wut.jmx.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@WebFilter(filterName = "employeeId", urlPatterns = "/*")
public class LoginFilter implements Filter {
    private static AntPathMatcher ANTPATHMATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();// backend/index.html
        log.info("当前请求路径为:{}", requestURI);
        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/doc.html",
                "/webjars/**",
                "/swagger-ui.html/**",
                "/swagger-resources/**",
                "/v2/**"
        };
    boolean check = check(urls,requestURI);
    if (check){
            log.info("当前路径");
            filterChain.doFilter(request,response);
            return;
        }
    if (request.getSession().getAttribute("employeeId")!=null){
        log.info("用户以登录，用户id为:{}",request.getSession().getAttribute("employeeId"));
        Long empId = Long.valueOf(request.getSession().getAttribute("employeeId").toString());
        BaseContext.setCurrentId(empId);
        filterChain.doFilter(request,response);
        return;
        }
    response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    return;
    }
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = ANTPATHMATCHER.match(url, requestURI);
            if (match == true) {
                return true;
            }
        }
        return false;
    }
}


